"""
calico
https://raw.githubusercontent.com/projectcalico/calico/v3.27.0/manifests/calico.yaml   ipip
https://raw.githubusercontent.com/projectcalico/calico/v3.27.0/manifests/calico-typha.yaml  bgp
https://docs.tigera.io/calico/latest/getting-started/kubernetes/self-managed-onprem/onpremises#install-calico-with-kubernetes-api-datastore-more-than-50-nodes

coreDNS
https://raw.githubusercontent.com/coredns/deployment/master/kubernetes/coredns.yaml.sed

nginx-ingress-controller
https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.2/deploy/static/provider/cloud/deploy.yaml
https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/mandatory.yaml

"""

from copy import deepcopy

import conf
from app.settings import BASE_DIR
from utils import write_file, read_from_file, clean_path

calico_3_27_ipip_module = read_from_file(
    "{}/deploy/module/plugin/calico3.27-ipip.yaml".format(BASE_DIR), encoding="gbk")
calico_3_20_ipip_module = read_from_file(
    "{}/deploy/module/plugin/calico3.20-ipip.yaml".format(BASE_DIR), encoding="gbk")

core_dns_1_9_module = read_from_file("{}/deploy/module/plugin/coreDNS1.9.yaml".format(BASE_DIR), encoding="gbk")

nginx_ingress_controller_1_8_module = read_from_file(
    "{}/deploy/module/plugin/nginx-ingress-controller1.8.yaml".format(BASE_DIR), encoding="gbk")
nginx_ingress_controller_1_3_module = read_from_file(
    "{}/deploy/module/plugin/nginx-ingress-controller1.3.yaml".format(BASE_DIR), encoding="gbk")
nginx_ingress_controller_0_30_module = read_from_file(
    "{}/deploy/module/plugin/nginx-ingress-controller0.30.yaml".format(BASE_DIR), encoding="gbk")

CALICO_YAML_NAME = "calico.yaml"
MODE_ENUM = ["ipip", "bgp"]
COREDNS_YAML_NAME = "coreDNS.yaml"
NGINX_INGRESS_CONTROLLER_YAML_NAME = "nginx-ingress-controller.yaml"


def gen_calico_yaml(out_dir, k8s_version, cluster_cidr, apiserver_host, apiserver_port, network_interface, mode="ipip"):
    """
    mode: ipip or bgp
    """
    k8s_version = int(str(k8s_version).split(".")[1])

    calico_yaml_content = ""
    if mode == "ipip":
        if k8s_version >= 23:
            calico_yaml_content = deepcopy(calico_3_27_ipip_module)
            replace_dict = dict(
                CNI_IMAGE=conf.CALICO_IMAGE["3.27"]["cni"],
                NODE_IMAGE=conf.CALICO_IMAGE["3.27"]["node"],
                CONTROLLER_IMAGE=conf.CALICO_IMAGE["3.27"]["controller"],
                CLUSTER_CIDR=cluster_cidr,
                APISERVER_HOST=apiserver_host,
                APISERVER_PORT=apiserver_port,
                NETWORK_INTERFACE=network_interface,
            )
        else:
            calico_yaml_content = deepcopy(calico_3_20_ipip_module)
            replace_dict = dict(
                CNI_IMAGE=conf.CALICO_IMAGE["3.20"]["cni"],
                NODE_IMAGE=conf.CALICO_IMAGE["3.20"]["node"],
                CONTROLLER_IMAGE=conf.CALICO_IMAGE["3.20"]["controller"],
                FLEXVOL_IMAGE=conf.CALICO_IMAGE["3.20"]["flexvol"],
                CLUSTER_CIDR=cluster_cidr,
                APISERVER_HOST=apiserver_host,
                APISERVER_PORT=apiserver_port,
                NETWORK_INTERFACE=network_interface,
            )

        for old, new in replace_dict.items():
            calico_yaml_content = calico_yaml_content.replace("--{}--".format(old), new)
    if mode == "bgp":
        # todo bgp mode calico deploy
        raise Exception("bgp的yaml配置还没写")
        pass

    path = clean_path(out_dir + "/" + CALICO_YAML_NAME)
    write_file(path, calico_yaml_content)
    return path


def gen_core_dns_yaml(out_dir, replicas, dns_svc_ip, resolve_list, upper_dns_server="/etc/resolve.conf"):
    core_dns_yaml_content = deepcopy(core_dns_1_9_module)

    replace_dict = dict(
        CLUSTER_DOMAIN="cluster.local",
        REVERSE_CIDRS="in-addr.arpa ip6.arpa",
        UPSTREAMNAMESERVER=str(upper_dns_server),
        HOSTS="\n".join(["{}{}".format(" " * 12, each) for each in resolve_list]),  # yaml对齐格式
        REPLICAS=str(replicas),
        COREDNS_IMAGE=conf.COREDNS_IMAGE["1.9"]["dns"],
        CLUSTER_DNS_IP=str(dns_svc_ip),
    )
    for old, new in replace_dict.items():
        core_dns_yaml_content = core_dns_yaml_content.replace("--{}--".format(old), new)

    path = clean_path(out_dir + "/" + COREDNS_YAML_NAME)
    write_file(path, core_dns_yaml_content)
    return path


def gen_nginx_ingress_controller_yaml(out_dir, k8s_version, replicas):
    k8s_version = int(str(k8s_version).split(".")[1])

    if k8s_version >= 22:
        nginx_ingress_controller_yaml_content = deepcopy(nginx_ingress_controller_1_8_module)
        replace_dict = dict(
            KUBE_WEBHOOK_CERTGEN_IMAGE=conf.NGINX_INGRESS_IMAGE["1.8"]["webhook_certgen"],
            CONTROLLER_IMAGE=conf.NGINX_INGRESS_IMAGE["1.8"]["controller"],
            REPLICAS=str(replicas),
        )
    elif k8s_version >= 19:
        nginx_ingress_controller_yaml_content = deepcopy(nginx_ingress_controller_1_3_module)
        replace_dict = dict(
            KUBE_WEBHOOK_CERTGEN_IMAGE=conf.NGINX_INGRESS_IMAGE["1.3"]["webhook_certgen"],
            CONTROLLER_IMAGE=conf.NGINX_INGRESS_IMAGE["1.3"]["controller"],
            REPLICAS=str(replicas),
        )
    else:
        nginx_ingress_controller_yaml_content = deepcopy(nginx_ingress_controller_0_30_module)
        replace_dict = dict(
            CONTROLLER_IMAGE=conf.NGINX_INGRESS_IMAGE["0.30"]["controller"],
            REPLICAS=str(replicas),
        )

    for old, new in replace_dict.items():
        nginx_ingress_controller_yaml_content = nginx_ingress_controller_yaml_content.replace("--{}--".format(old), new)

    path = clean_path(out_dir + "/" + NGINX_INGRESS_CONTROLLER_YAML_NAME)
    write_file(path, nginx_ingress_controller_yaml_content)
    return path
